#!/bin/bash
# This script prepares the Fortran source code for flang-7, which cannot resolve the generic
# procedure defined in common/evaluate.f90.
# Usage: flsrc DIR

# The full path of the directory to proceed
DIR="$(realpath "$1")"

# Exit if DIR is not a testing directory.
if ! basename "$DIR" | grep -q "\.test\|test\.\|\.tst\|tst\." || ! [[ -d "$DIR" ]] ; then
    printf "\n%s is not a testing directory.\n\nExit.\n\n" "$DIR"
    exit 1
fi

# Temporary file
TMPF="/tmp/tmp.$(date +%s)"

# The solver
SOLVER="$(basename "$DIR" | sed 's/test\.//' | sed 's/\.test//')"

# The files that need preprocessing.
EVALUATEF90="evaluate.f90"
EVALUATE="$DIR/common/$EVALUATEF90"

sed -e '/^\s*interface evaluate\s*$/,+4d' "$EVALUATE" > "$TMPF"
cat "$TMPF" > "$EVALUATE"
sed -i 's/^\s*public :: evaluate\s*$/public :: evaluatef, evaluatefc/' "$EVALUATE"

if [[ "$SOLVER" = "cobyla" ]] ; then
    sed -i 's/evaluate_mod, only : evaluate/evaluate_mod, only : evaluatefc/' "$SOLVER"/*.f90
    sed -i 's/call evaluate(calcfc/call evaluatefc(calcfc/g' "$SOLVER"/*.f90
else
    sed -i 's/evaluate_mod, only : evaluate/evaluate_mod, only : evaluatef/' "$SOLVER"/*.f90
    sed -i 's/call evaluate(calfun/call evaluatef(calfun/g' "$SOLVER"/*.f90
fi

exit 0
